<template>
  <div class="guild-member-manage">
    <h2>公会成员管理</h2>
    <el-table :data="members" style="width: 100%" border>
      <el-table-column prop="id" label="成员ID" align="center"></el-table-column>
      <el-table-column prop="guildId" label="公会ID" align="center"></el-table-column>
      <el-table-column prop="playerId" label="玩家ID" align="center"></el-table-column>
      <el-table-column prop="joinTime" label="加入时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.joinTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="position" label="职位" align="center"></el-table-column>
      <el-table-column prop="isApproved" label="审核状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.isApproved === 1 ? 'success' : 'warning'">
            {{ scope.row.isApproved === 1 ? '已审核' : '待审核' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button size="mini" type="primary" @click="approveMember(scope.row.id)" v-if="scope.row.isApproved !== 1">审核通过</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="showCreateDialog">添加成员</el-button>
      <el-button @click="fetchAllMembers">查询所有成员</el-button>
      <el-input
          v-model="searchGuildId"
          placeholder="按公会ID筛选"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchMembersByGuildId"
      />
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />
    </div>

    <!-- 成员表单对话框 -->
    <el-dialog title="添加成员" v-model="dialogVisible" width="30%">
      <el-form :model="memberForm" :rules="rules">
        <el-form-item label="公会ID">
          <el-input v-model="memberForm.guildId" disabled v-if="!isEdit" />
        </el-form-item>
        <el-form-item label="玩家ID">
          <el-input v-model="memberForm.playerId" />
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="memberForm.position" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="memberForm.isApproved">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="加入时间" prop="joinTime">
          <el-date-picker
              v-model="memberForm.joinTime"
              type="datetime"
              placeholder="选择加入时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑成员对话框 -->
    <el-dialog title="编辑成员" v-model="editDialogVisible" width="30%">
      <el-form :model="editMemberForm" :rules="rules">
        <el-form-item label="公会ID">
          <el-input v-model="editMemberForm.guildId" disabled />
        </el-form-item>
        <el-form-item label="玩家ID">
          <el-input v-model="editMemberForm.playerId" />
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="editMemberForm.position" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editMemberForm.isApproved">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="加入时间" prop="joinTime">
          <el-date-picker
              v-model="editMemberForm.joinTime"
              type="datetime"
              placeholder="选择加入时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateMember">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

const members = ref([]);
const loading = ref(false);
const searchGuildId = ref('');

const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const isEdit = ref(false);

const memberForm = ref({
  id: null,
  guildId: '',
  playerId: '',
  position: '',
  isApproved: 0,
  joinTime: null
});

const editMemberForm = ref({
  id: null,
  guildId: '',
  playerId: '',
  position: '',
  isApproved: 0,
  joinTime: null
});

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表单验证规则
const rules = {
  guildId: [{ required: true, message: '请输入公会ID', trigger: 'blur' }],
  playerId: [{ required: true, message: '请输入玩家ID', trigger: 'blur' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  joinTime: [{ required: true, message: '请选择加入时间', trigger: 'change' }]
};

const formatDate = (dateString) => {
  if (!dateString) return '从未登录';
  try {
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
  } catch (error) {
    return '时间格式错误';
  }
};

// 获取所有成员（分页）
const fetchAllMembers = async () => {
  try {
    loading.value = true;
    const response = await request.get('/guild/members/all', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    if (response.data && response.data.records) {
      members.value = response.data.records.map(member => ({
        ...member,
        joinTime: member.joinTime ? dayjs(member.joinTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      total.value = response.data.total;
    } else {
      members.value = [];
      total.value = 0;
    }
    ElMessage.success('获取所有成员成功');
  } catch (error) {
    console.error('获取所有成员失败:', error);
    ElMessage.error('获取所有成员失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 根据公会ID获取成员列表（分页）
const fetchMembersByGuildId = async () => {
  const guildId = searchGuildId.value.trim();
  if (!guildId) {
    ElMessage.warning('请输入公会ID');
    return;
  }
  try {
    loading.value = true;
    const response = await request.get(`/guild/${guildId}/members`, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    if (response.data && response.data.records) {
      members.value = response.data.records.map(member => ({
        ...member,
        joinTime: member.joinTime ? dayjs(member.joinTime).format('YYYY-MM-DD HH:mm:ss') : null
      }));
      total.value = response.data.total;
    } else {
      members.value = [];
      total.value = 0;
    }
    ElMessage.success(`获取公会ID为 ${guildId} 的成员成功`);
  } catch (error) {
    console.error('获取成员列表失败:', error);
    ElMessage.error('获取成员列表失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 显示创建对话框
const showCreateDialog = (guildId = '') => {
  dialogVisible.value = true;
  isEdit.value = false;
  memberForm.value = {
    id: null,
    guildId: guildId,
    playerId: '',
    position: '',
    isApproved: 0,
    joinTime: dayjs().format('YYYY-MM-DD HH:mm:ss') // 默认当前时间
  };
};

// 显示编辑对话框
const showEditDialog = (member) => {
  editDialogVisible.value = true;
  isEdit.value = true;

  // 确保时间格式正确
  editMemberForm.value = {
    ...member,
    joinTime: member.joinTime ? dayjs(member.joinTime).format('YYYY-MM-DD HH:mm:ss') : null
  };
};

// 提交添加成员表单
const submitForm = async () => {
  try {
    // 表单验证
    await memberForm.value.joinTime;

    const response = await request.post('/guild/member', memberForm.value);
    if (response.code === 200) {
      ElMessage.success('添加成员成功');
      dialogVisible.value = false;
      // 刷新成员列表
      await fetchAllMembers();
    } else {
      ElMessage.error(response.message || '添加成员失败');
    }
  } catch (error) {
    console.error('添加成员出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 提交编辑成员表单
const updateMember = async () => {
  try {
    // 表单验证
    if (!editMemberForm.value.joinTime) {
      throw new Error('请选择加入时间');
    }

    const response = await request.put('/guild/member', editMemberForm.value);
    if (response.code === 200) {
      ElMessage.success('更新成员成功');
      editDialogVisible.value = false;
      // 刷新成员列表
      await fetchAllMembers();
    } else {
      ElMessage.error(response.message || '更新成员失败');
    }
  } catch (error) {
    console.error('更新成员出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 删除成员
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该成员吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await request.delete(`/guild/member/${id}`);
    if (response.code === 200) {
      ElMessage.success('删除成员成功');
      // 刷新成员列表
      await fetchAllMembers();
    } else {
      ElMessage.error(response.message || '删除成员失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除成员出错，请检查控制台日志');
    }
  }
};

// 审核通过成员
const approveMember = async (id) => {
  try {
    const response = await request.put(`/guild/member/${id}/approve`);
    if (response.code === 200) {
      ElMessage.success('审核通过');
      // 刷新成员列表
      await fetchAllMembers();
    } else {
      ElMessage.error(response.message || '审核失败');
    }
  } catch (error) {
    ElMessage.error('审核成员出错，请检查控制台日志');
  }
};

// 分页事件处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchAllMembers();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchAllMembers();
};

onMounted(() => {
  fetchAllMembers();
});
</script>

<style scoped>
.guild-member-manage {
  padding: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>